<template>
	<div class="tui-conversation" @click="handleClickConv" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
		<TUISearch searchType="global" />
		<ConversationHeader v-if="isShowConversationHeader" ref="headerRef" />
		<ConversationNetwork />
		<ConversationList class="tui-conversation-list" ref="conversationListDomRef"
			@handleSwitchConversation="handleSwitchConversation" @getPassingRef="getPassingRef" />
	</div>
</template>


<script lang="ts">
	export default {
		data() {
			return {
				loading: false,
				iskf: null,
				to_mobile: null,
				type: null,
				mobile: '',
			}
		},
		onLoad(payload : any,) {
			const that = this
			that.iskf = payload.iskf
			that.to_mobile = payload.to_mobile
			that.type = payload.type
			that.mobile = payload.mobile
		},
		onShow() {
			console.log(this.mobile)
			let chat1 = TencentCloudChat.create({
				SDKAppID: 1400818966 // Replace `0` with the `SDKAppID` of your Chat app during access.
			});
			// chat1.destroy();
			// TUIChatKit 初始化
			TUIChatKit.init();
			const config = {
				userID: this.mobile, // User ID
				SDKAppID: 1400818966, // Your SDKAppID
				secretKey: 'fbb62384b4544dbb81878e6af400affada719aecb9ddebe6c1221868f959635c', // Your secretKey
			};
			let Sig = genTestUserSig(config).userSig;
			console.log(config.userID)
			let promise = chat1.login({ userID: config.userID, userSig: Sig });
			promise.then(function (imResponse) {
				console.log(imResponse.data); // 登录成功
				if (imResponse.data.repeatLogin === true) {
					// 标识账号已登录，本次登录操作为重复登录。
					console.log(imResponse.data.errorInfo);
				}
			}).catch(function (imError) {
				console.warn('login error:', imError); // 登录失败的相关信息
			});
			const chat2 = computed(() => { return store.state.im.chat });
			chat2.value.isReady();
			// var that = this
			//    setTimeout(function(){
			// 	that.loading = true
			// },1500)
		},
	}
</script>
<script lang="ts" setup>
	import {
		PERFIX,
		kfs,
		IM_SDKAppID
	} from '@/config/app';
	import TencentCloudChat from '@tencentcloud/chat';
	import {
		TUIChatKit,
		genTestUserSig,
	} from "TUIKit";
	import { TUIStore, StoreName, TUIConversationService } from "@tencentcloud/chat-uikit-engine";
	import { ref, onMounted, reactive, onBeforeMount, getCurrentInstance, computed, onUnmounted } from "../../adapter-vue";
	import { TUIGlobal } from "../../utils/universal-api/index";
	import ConversationList from "./conversation-list/indexlist.vue";
	// import ConversationHeader from "./conversation-header/index.vue";
	import ConversationNetwork from "./conversation-network/index.vue";
	import { onHide } from "@dcloudio/uni-app"; // 该方法只能用在父组件内，子组件内不生效
	import store from '@/store/index.js';
	// #ifdef MP-WEIXIN
	import "./subPackage-init.ts";
	// #endif
	const emits = defineEmits(["handleSwitchConversation"]);
	const totalUnreadCount = ref(0);
	const headerRef = ref<HTMLElement | undefined>();
	const conversationListDomRef = ref<HTMLElement | undefined>();
	const touchX = ref<number>(0);
	const touchY = ref<number>(0);
	const isShowConversationHeader = ref<boolean>(true);


	const chat = computed(() => { return store.state.im.chat });
	const getCurrent = getCurrentInstance();
	// #ifdef MP
	onMounted(() => {
		let isReady = chat.value.isReady();
		if (isReady) {
			toDetail();
		}
		chat.value.on(TencentCloudChat.EVENT.SDK_READY, function () {
			toDetail();
		});

	})
	// #endif

	const toDetail = () => {
		const params = getCurrent.data;
		if (!params.to_mobile) {
			return
		}
		// 聊天的userID
		const userID = params.iskf === 'true' ? kfs[0] : PERFIX + params.to_mobile;
		const conversationID = `C2C${userID}`;
		TUIConversationService.getConversationProfile(conversationID)
			.then((res) => {
				console.log('createC2CConversation-success', res)
				TUIConversationService.switchConversation(
					res.data.conversation.conversationID
				);
				uni.navigateTo({
					url: '/TUIKit/components/TUIChat/index'
				});
			})
			.catch((err) => {
				// uni.showToast({
				// 	title: "The other party has not registered for a chat service",
				// 	icon: 'none'
				// })
				console.warn("打开会话失败", err.code, err.msg);
				const userID2 = kfs[0];
				const conversationID2 = `C2C${userID2}`;
				TUIConversationService.getConversationProfile(conversationID2)
					.then((res) => {
						console.log('createC2CConversation-success', res)
						TUIConversationService.switchConversation(
							res.data.conversation.conversationID
						);
						uni.navigateTo({
							url: '/TUIKit/components/TUIChat/index'
						});
					}).catch((err) => {
						console.warn("打开会话失败", err.code, err.msg);
					});
			});
	}
	TUIStore.watch(StoreName.CONV, {
		totalUnreadCount: (count : number) => {
			totalUnreadCount.value = count;
		},
	});

	TUIStore.watch(StoreName.CUSTOM, {
		isShowConversationHeader: (showStatus : boolean) => {
			isShowConversationHeader.value = showStatus !== false;
		},
	});


	onUnmounted(() => {

		TUIStore.unwatch(StoreName.CONV, {
			totalUnreadCount: (count : number) => {
				totalUnreadCount.value = count;
			},
		});

		TUIStore.unwatch(StoreName.CUSTOM, {
			isShowConversationHeader: (showStatus : boolean) => {
				isShowConversationHeader.value = showStatus !== false;
			},
		});
	});

	const handleSwitchConversation = (conversationID : string) => {
		TUIGlobal?.navigateTo({
			url: "/TUIKit/components/TUIChat/index",
		});
		emits("handleSwitchConversation", conversationID);
	};

	const closeChildren = () => {
		headerRef?.value?.closeChildren();
		conversationListDomRef?.value?.closeChildren();
	};

	const handleClickConv = () => {
		closeChildren();
	};

	onHide(closeChildren);

	const handleTouchStart = (e : any) => {
		touchX.value = e.changedTouches[0].clientX;
		touchY.value = e.changedTouches[0].clientY;
	};

	const handleTouchEnd = (e : any) => {
		let x = e.changedTouches[0].clientX;
		let y = e.changedTouches[0].clientY;
		let turn = "";
		if (x - touchX.value > 50 && Math.abs(y - touchY.value) < 50) {
			//右滑
			turn = "right";
		} else if (x - touchX.value < -50 && Math.abs(y - touchY.value) < 50) {
			//左滑
			turn = "left";
		}
		if (y - touchY.value > 50 && Math.abs(x - touchX.value) < 50) {
			//下滑
			turn = "down";
		} else if (y - touchY.value < -50 && Math.abs(x - touchX.value) < 50) {
			//上滑
			turn = "up";
		}
		//根据方向进行操作
		if (turn === "down" || turn === "up") {
			closeChildren();
		}
	};

	const getPassingRef = (ref) => {
		ref.value = conversationListDomRef.value;
	}
</script>

<style lang="scss" scoped src="./style/index.scss"></style>